package util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	
	private static Transaction t = null;
	
	private static Session session = null;
	
	private static SessionFactory sessionFactory = null;
	
	static{
		
		try{
			sessionFactory = new Configuration().configure().buildSessionFactory();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	public static Session prepareSession(){
		if(sessionFactory!=null)
			return sessionFactory.openSession();
		else{
			
			sessionFactory = new Configuration().configure().buildSessionFactory();
			return sessionFactory.openSession();
		}
		
		
	}
	
	public static void closeSession(Session session){
		if(session!=null && session.isOpen())
		session.close();
	}
	
	public static void startTransaction(Session session){
		
		 t = session.beginTransaction();
		if(t!=null){
			t.begin();
		}
	}
	
	public static void commitTransaction(){
		if(t!=null){
			t.commit();
			t = null;
		}
	}
	
	public static void rollbackTransaction(){
		if(t!=null){
			t.rollback();
		}
	}

}
